<template>
  <div class="fbDrawer">
    <beetles-drawer title="新增账户" :visible.sync="visible" :before-close="handleClose" :auto-size="true"
                    :close-on-press-escape="false"
                    :wrapperClosable="false"
                    :modal-append-to-body="false">
      <div style="flex: auto; overflow: scroll; border-top: solid 2px #e8e8e8;margin: 0 auto;padding: 10px" ref="main">
        <el-form :model="monitorForm" ref="monitorForm" :rules="monitorForm.rules" v-loading="loading">
          <el-table :data="monitorForm.monitorData" style="width: 100%" class="monitor-table"
                    :header-cell-style="{color:'#101010'}" size="small">
            <el-table-column type="index" align="center" width="40px" label="#" fixed></el-table-column>
            <el-table-column prop="name" label="账户名称" width="150px">
              <template slot-scope="scope">
                <el-form-item :prop="'monitorData.'+scope.$index + '.name'" :rules="monitorForm.rules.name">
                  <el-input size="mini" placeholder="请输入账户名" v-model="scope.row.name"></el-input>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column prop="platformId" label="账户ID" width="180px">
              <template slot-scope="scope">
                <el-form-item :prop="'monitorData.'+scope.$index + '.platformId'" :rules="monitorForm.rules.platformId">
                  <el-input size="mini" placeholder="请输入账户ID"
                            v-model="scope.row.platformId"></el-input>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column prop="offerId" label="订单名称" width="150px">
              <template slot-scope="scope">
                <el-form-item :prop="'monitorData.'+scope.$index + '.offerId'" :rules="monitorForm.rules.offerId">
                  <el-select filterable size="mini" clearable v-model="scope.row.offerId"
                             placeholder="请选择订单名称">
                    <el-option v-for="(item,index) in offerList" :key="index" :value="item.id" :label="item.name === '同上'?item.name:item.name+' ID:'+item.id"
                               :disabled="scope.$index === 0  && item.name === '同上'"
                    >
                    </el-option>
                  </el-select>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column prop="platform" label="媒体" width="130px">
              <template slot-scope="scope">
                <el-form-item :prop="'monitorData.'+scope.$index + '.platform'" :rules="monitorForm.rules.platform">
                  <el-select size="mini" clearable v-model="scope.row.platform" placeholder="请选择媒体"
                             :disabled="disabledPlatform">
                    <el-option v-for="(item,index) in advAddPlatform" :key="index" :value="item.dictKey"
                               :label="item.dictValue"
                               :disabled="scope.$index === 0  && item.dictValue === '同上'"
                    >
                    </el-option>
                  </el-select>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column prop="platformId" label="代理" width="110px">
              <template slot-scope="scope">
                <el-form-item :prop="'monitorData.'+scope.$index + '.agencyName'" :rules="monitorForm.rules.agencyName">
                  <el-input size="mini" placeholder="请选择代理"
                            v-model="scope.row.agencyName"></el-input>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column prop="owner" label="账户所有人" width="150px">
              <template slot-scope="scope">
                <el-form-item :prop="'monitorData.'+scope.$index + '.owner'" :rules="monitorForm.rules.owner">
                  <el-select size="mini" filterable clearable v-model="scope.row.owner"
                             placeholder="请选择账户所有人">
                    <el-option v-for="(item,index) in userList" :key="index" :value="item.id" :label="item.realName"
                               :disabled="scope.$index === 0  && item.realName === '同上'"
                    >
                    </el-option>
                  </el-select>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column prop="operator" label="账户运营人" width="150px">
              <template slot-scope="scope">
                <el-form-item :prop="'monitorData.'+scope.$index + '.operator'" :rules="monitorForm.rules.operator">
                  <el-select size="mini" filterable clearable v-model="scope.row.operator"
                             placeholder="请选择账户运营人">
                    <el-option v-for="(item,index) in userList" :key="index" :value="item.id" :label="item.realName"
                               :disabled="scope.$index === 0  && item.realName === '同上'"
                    >
                    </el-option>
                  </el-select>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column align="center" width="50px" label="操作" fixed="right">
              <template slot-scope="scope">
                <div style="text-align: center;font-size: 25px" @click="delRow(scope.$index)" class="delBtn">
                  <i class="el-icon-circle-close"></i>
                </div>
              </template>
            </el-table-column>
          </el-table>
        </el-form>

        <div class="addBtn" @click="add" v-if="!disabledPlatform">
          <div style="margin-right: 20px">
            <i class="el-icon-circle-plus-outline"></i>
          </div>
          <div>
            添加账户
          </div>
        </div>
      </div>
      <template #footer>
        <div style="display: flex;justify-content: center;align-items: center">
          <el-button size="medium" type="primary" plain @click="submit"
                     :disabled="!monitorForm.saving && monitorForm.monitorData.length === 0 ">保存
          </el-button>
          <el-button size="medium" @click="handleClose">
            取消
          </el-button>
        </div>
      </template>
    </beetles-drawer>
  </div>
</template>

<script>
import {getSysDictList} from "@/api/system/dict";
import {getUrlData} from '@/api/system/dict';
import {batchAddAccounts} from "@/api/business/account"
import {findObjectList} from "@/util/util";
import BeetlesDrawer from "@/components/beetles/beetles-drawer";
import {Message} from "element-ui";
import { deepClone } from "@/util/util";

export default {
  name: "accountAdd",
  components: {BeetlesDrawer},
  props: {
    visible: {
      type: Boolean
    },
    account: {
      type: Object
    },
    // advAddPlatform: {
    //   type: Array
    // },
    // userList: {
    //   type: Array
    // },
    // offerList: {
    //   type: Array
    // },
  },
  data() {
    return {
      loading: false,
      disabledPlatform: false,
      advAddPlatform: [],
      userList: [],
      offerList: [],
      bindStatusList: [
        {label: '同上', value: 'up'},
        {label: '已绑定', value: 0},
        {label: '解绑', value: 1},
        {label: '被禁止', value: 2}
      ],
      statusList: [
        {label: '同上', value: 'up'},
        {label: '开启', value: 0},
        {label: '关闭', value: 1}
      ],
      monitorForm: {
        saving: false,
        monitorData: [],
        rules: {
          name: [
            {required: true, message: '请输入账户名称', trigger: 'change', validator: this.checkLength}
          ],
          platformId: [
            {required: true, trigger: 'blur', validator: this.checkPlatform}
          ],
          offerId: [
            {required: true, message: '请选择订单名称', trigger: 'change'}
          ],
          platform: [
            {required: true, message: '请选择媒体', trigger: 'change'}
          ],
          // owner: [
          //   {required: true, message: '请选择账户所有人', trigger: 'change'}
          // ],
          operator: [
            {required: true, message: '请选择账户运营人', trigger: 'change'}
          ],
          status: [
            {required: true, message: '请选择状态', trigger: 'change'}
          ],
          agencyName: [{required: true, message: '请输入代理', trigger: "blur"}]
        },
      },
      agencyNameList:[]
    }
  },
  created() {
    this.init();
    this.onLoad()
    this.getAgencyNameList()
  },
  computed: {
    getSize() {
      return window.innerWidth > 1300 ? '1250' : '80%';
    }
  },
  methods: {
    async init() {
      const {platforms} = await getSysDictList('platforms')
      this.advAddPlatform = deepClone(platforms)
      if (!(this.advAddPlatform.findIndex(item => item.dictValue === '同上') >= 0)) {
        this.advAddPlatform.unshift({dictKey: 'up', dictValue: '同上'})
      }
      const res1 = await getUrlData('/api/beetles-business/offer/get-select')
      this.offerList = deepClone(res1.data.data);
      if (!(this.offerList.findIndex(item => item.realName === '同上') >= 0)) {
        this.offerList.unshift({id: 'up', name: '同上'})
      }
      const res2 = await getUrlData('/api/blade-user/select/user')
      this.userList = deepClone(res2.data.data)
      if (!(this.userList.findIndex(item => item.realName === '同上') >= 0)) {
        this.userList.unshift({id: 'up', realName: '同上'})
      }
      console.log('init')
    },
    delRow(i) {
      if (this.monitorForm.monitorData.length - 1 > i) {
        for (const key in this.monitorForm.monitorData[i]) {
          if (this.monitorForm.monitorData[i][key] !== 'up' && this.monitorForm.monitorData[i + 1][key] === 'up') {
            this.monitorForm.monitorData[i + 1][key] = this.monitorForm.monitorData[i][key]
          }
        }
      }
      this.monitorForm.monitorData.splice(i, 1)
    },

    add() {
      // console.log("add");
      // this.loading = true;
      if (this.monitorForm.monitorData.length >= 1) {
        this.monitorForm.monitorData.push({
          bindStatus: 0,
          operator: "up",
          owner: "up",
          offerId: "up",
          platform: "up",
          agencyName:"Ads4each",
          status: 0
        })
      } else {
        this.monitorForm.monitorData.push({
          bindStatus: 0,
          status: 0,
          owner: this.getOwner(),
        })
      }
      console.log('add', this.monitorForm.monitorData)
      this.$nextTick(() => {
        // console.log(this.$refs.main.scrollHeight)

        this.$refs.main.scrollTop = this.$refs.main.scrollHeight;
      })
      // this.loading = false;
      // console.log("add2");
    },
    onLoad() {
      this.loading = true;
      let data = this.account;
      let list = []
      if (data.accounts && data.accounts.length > 0) {
        data.accounts.forEach(item => {
          list.push({
            name: item.name,
            platformId: item.platformId,
            platform: data.platform,
            bindStatus: 0,
            status: 0
          })
        })
      } else {
        list.push({
          bindStatus: 0,
          status: 0,
          agencyName:"Ads4each"
        });
      }
      this.disabledPlatform = !!data.platform;
      this.monitorForm.monitorData = list;
      // this.translateToTable();
      this.loading = false;
    },
    translateToTable() {
      let data = JSON.parse(JSON.stringify(this.monitorForm.monitorData))
      data.map((item, index) => {
        for (const key in item) {
          if (key !== 'name' && key !== 'platformId' && index > 0) {
            if (item[key] === this.monitorForm.monitorData[index - 1][key]) {
              item[key] = 'up'
            }
          }
        }
      })
      this.monitorForm.monitorData = data
    },
    translateToData() {
      let data = JSON.parse(JSON.stringify(this.monitorForm.monitorData))
      data.map((item, index) => {
        for (const key in item) {
          if (item[key] === 'up') {
            item[key] = data[index - 1][key]
          }
        }
      })
      return data
    },
    submit() {
      if (this.loading) {
        return;
      }
      // this.loading = true;
      this.$refs.monitorForm.validate((valid, obj) => {
        if (valid) {
          batchAddAccounts(this.translateToData()).then(res => {
            if (res.data.code === 200) {
              this.monitorForm.monitorData = [];
              this.$message.success('新增成功!')
              this.$emit('submit')
              // this.loading = false;
            } else {
              // this.loading = false;
            }
          }).catch(() => {
            // this.loading = false;
          })
        } else {
          // this.$message({
          //   message: '存在不合法数据，请检查',
          //   type: 'error'
          // })
          // this.loading = false;
        }
      })
    },
    handleClose() {
      // this.loading = false;
      this.monitorForm.monitorData = [];
      this.$emit('close')
    },
    checkLength(rule, value, callback) {
      if (value != null) value = value.trim();
      if (value == null || value.length == 0) {
        return callback(new Error('内容不能为空'))
      }
      if (value.length > 100) {
        return callback(new Error('内容超长'))
      }
      callback();
    },
    checkPlatform(rule, value, callback) {
      let index = rule.field.split(".")[1];
      let row = this.monitorForm.monitorData[index];
      let platform = row.platform;
      let platformId = row.platformId;
      if (platformId == null || platformId === '') {
        return callback(new Error("请输入账户ID"))
      }
      if (platform && platform === 'up' && index > 0) {
        for (let i = index - 1; i >= 0; i--) {
          let currPlatform = this.monitorForm.monitorData[i].platform;
          if (currPlatform !== 'up') {
            platform = currPlatform;
            break;
          }
        }
      }

      if (platform != null && platform !== '') {
        let accountRegex = null;
        let errMsg = null;
        if (platform.toLowerCase() === 'google') {
          accountRegex = /^[\d]{3}-[\d]{3}-[\d]{4}$/
          errMsg = '账户格式应为 111-222-3333';
        } else {
          accountRegex = /^[\d]+$/
          errMsg = '账户格式应为纯数字';
        }
        if (!accountRegex.test(platformId)) {
          return callback(new Error(errMsg))
        }
      }
      callback();
    },
    getOwner: function () {
      this.userList.find((v) => {
        if (v.realName === 'Ads4each') {
          return v.id;
        }
      })
      return null;
    },
    async getAgencyNameList() {
      const {agency_list} = await getSysDictList('agency_list')
      this.agencyNameList = agency_list.map(item => {
        return {
          label: item.dictValue,
          value: item.dictValue
        }
      })
    }
  },
  watch: {
    // account:{
    //   deep:true,
    //   handler(val){
    //     if(val){
    //       this.onLoad();
    //     }
    //   }
    // }
  },
}
</script>

<style scoped lang="scss">
/deep/ .el-drawer.rtl {
  //overflow: hidden;
}

/deep/ .el-drawer {
  outline: none;

  &__body {
    height: 100%;
    overflow: hidden;
  }
}

.monitor-table {
  ///deep/ .el-form-item {
  //  margin-bottom: 0;
  //}
}

.delBtn {
  &:hover {
    color: #78aff9;
  }
}

.addBtn {
  width: 100px;
  margin-top: 2em;
  margin-left: 2em;
  display: flex;
  color: #34A9FF;
  cursor: pointer;

  &:hover {
    color: #78aff9;
  }
}
</style>
